package com.mew.lobby.net;

import com.mew.lobby.provide.ServerRegisterFeignService;
import com.zebra.remoting.config.TmsServerInfo;
import com.zebra.remoting.protocol.CommandModel;
import com.zebra.remoting.protocol.CommandModelManager;
import com.zebra.remoting.protocol.CommandProfile;
import com.zebra.remoting.protocol.CommandType;
import com.zebra.remoting.tms.TmsConfigInfoManager;
import com.zebra.remoting.tms.TmsToRegisterMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author King.Song
 * @Date 2020/10/9 0009
 **/
@Component
@Order(2)
@Slf4j
public class StartAfterInitialize implements ApplicationRunner {

    @Autowired
    private ServerRegisterFeignService serverRegisterFeignService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (null == TmsConfigInfoManager.getInstance().getServerInfo() || StringUtils.isEmpty(TmsConfigInfoManager.getInstance().getServerInfo().getCmds())){
            throw  new Exception("Start serverId is null or cms is null!");
        }

        if (StringUtils.isEmpty(TmsConfigInfoManager.getInstance().getServerInfo().getInIP()) || StringUtils.isEmpty(TmsConfigInfoManager.getInstance().getServerInfo().getOutIP())){
            throw  new Exception("start server ip-in or out is null! "+ TmsConfigInfoManager.getInstance().getServerInfo().toString());
        }
        log.info("StartAfter send register msg {}", TmsConfigInfoManager.getInstance().getServerInfo().toString());
        TmsToRegisterMessage toRegisterMessage = new TmsToRegisterMessage();
        toRegisterMessage.setServerInfo(TmsConfigInfoManager.getInstance().getServerInfo());
        List<CommandProfile> cmdList = CommandModelManager.buildCommandModels().stream().filter(c -> !CommandType.BASIS.equals(c.getCommandType())).map(CommandModel::toProfile).collect(Collectors.toList());
        toRegisterMessage.setCmds(cmdList);
        TmsServerInfo serverInfo = serverRegisterFeignService.registerServerAndRedis(toRegisterMessage);
        if (null == serverInfo){
            throw  new Exception("start server register exception! "+ TmsConfigInfoManager.getInstance().getServerInfo().toString());
        }
        TmsConfigInfoManager.getInstance().setServerInfo(serverInfo);
    }


}
